package com.heima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDTO;
import com.heima.model.wemedia.vo.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.mapper.WmUserMapper;
import com.heima.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //判断用户密码或者用户是否存在
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或者密码为空");
        }
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.<WmUser>lambdaQuery();
        //根据name去查询数据库，是否能查到
        wrapper.eq(WmUser::getName,dto.getName());
        WmUser wmUser = this.getOne(wrapper);
        if (wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");

        }
        String password = wmUser.getPassword();
        //对密码进行MD5加密，再进行判断
        String salt = wmUser.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
//
//        2. 检查密码是否正确
        if (!password.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误！！！");
        }
//        检查用户状态是否有效
        if(wmUser.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户的状态不对");
        }
        //更新登录的时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        HashMap map = new HashMap<>();
        try {
            //设置token,将生成得token发送给浏览器，让浏览器保留，这是也将自己得信息保留
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            WmUserVO wmUserVO = new WmUserVO();
            BeanUtils.copyProperties(wmUserVO,wmUser);

            map.put("token",token);
            map.put("user",wmUserVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(map);

    }
}
